class Solution {
public:
    struct State{
        int x,y,dis;
        State(int x,int y,int dis)
            :x(x)
            ,y(y)
            ,dis(dis)
        {}
        bool operator < (const State &p) const {
            return dis>p.dis;
        }
    };
    int dx[4]={0,0,1,-1};
    int dy[4]={1,-1,0,0};
    int f[60][60]={0};
    int vis[60][60]={0};

    int minTimeToReach(vector<vector<int>>& moveTime) {
        int n=moveTime.size(),m=moveTime[0].size();
        memset(f,0x3f3f3f3f,sizeof(f));
        priority_queue<State> q;
        f[0][0]=0;
        q.push({0,0,0});
        while(q.size())
        {
            State u=q.top();
            q.pop();
            if(vis[u.x][u.y])
            {
                continue;
            }
            vis[u.x][u.y]=1;
            for(int i=0;i<4;i++)
            {
                int nx=u.x+dx[i];
                int ny=u.y+dy[i];
                if(nx<0 || nx>=n || ny<0 || ny>=m || vis[nx][ny])
                {
                    continue;
                }
                int dist=max(f[u.x][u.y],moveTime[nx][ny])+1;
                if(f[nx][ny]>dist)
                {
                    f[nx][ny]=dist;
                    q.push({nx,ny,f[nx][ny]});
                }
            }
        }
        return f[n-1][m-1];

    }
};
